<template>
  <div class="ai-image-generator">
    <div class="container">
      <!-- 主内容区 - AI生图区域 -->
      <div class="main-content">
        <div class="main-header">
          <h1 class="main-title">AI创意图像生成器</h1>
          <p class="main-subtitle">上传参考文档并输入描述，生成您想象中的图像</p>
        </div>

        <div class="image-area" ref="imageAreaRef">
          <div v-if="!generatedImage" class="image-placeholder">
            <div class="icon">🖼️</div>
            <p>生成的图像将显示在这里</p>
            <p class="text-muted">请上传参考文档并输入描述词</p>
          </div>
          <img
            v-if="generatedImage"
            :src="generatedImage"
            alt="AI生成的图像"
            class="generated-image"
          />
        </div>

        <div class="image-controls">
          <button class="btn btn-secondary" :disabled="!generatedImage" @click="downloadImage">
            <span>下载图片</span>
          </button>
          <button class="btn btn-primary" :disabled="isGenerating" @click="generateImage">
            <span v-if="isGenerating" class="loading"></span>
            <span>{{ isGenerating ? '生成中...' : '生成图像' }}</span>
          </button>
        </div>
      </div>

      <!-- 侧边栏 -->
      <div class="sidebar">
        <div class="upload-area">
          <div
            class="upload-box"
            @click="triggerFileSelect"
            @dragover.prevent="handleDragOver"
            @dragleave="handleDragLeave"
            @drop.prevent="handleDrop"
            :class="{ 'drag-over': isDragOver }"
          >
            <div class="upload-icon">📄</div>
            <p class="upload-text">点击或拖拽文件到此处上传</p>
            <p class="text-muted">支持DOC、DOCX、XLS、XLSX格式</p>
          </div>

          <input
            ref="fileInputRef"
            type="file"
            multiple
            accept=".doc,.docx,.xls,.xlsx,.pdf"
            style="display: none"
            @change="handleFileSelect"
          />

          <div class="file-list">
            <div v-for="(file, index) in uploadedFiles" :key="index" class="file-item">
              <div class="file-icon">{{ getFileIcon(file.name) }}</div>
              <div class="file-info">
                <div class="file-name">{{ file.name }}</div>
                <div class="file-size">{{ formatFileSize(file.size) }}</div>
              </div>
              <button class="remove-btn" @click="removeFile(index)">×</button>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-header">
            <h2 class="input-title">图像描述</h2>
            <p class="input-subtitle">详细描述您想要生成的图像内容</p>
          </div>

          <div class="prompt-container">
            <textarea
              v-model="promptText"
              class="prompt-input"
              placeholder="例如：一只在太空中的猫，戴着宇航员头盔，背景是地球和星星..."
            ></textarea>
          </div>

          <div class="input-controls">
            <button class="btn btn-secondary" @click="clearPrompt">
              <span>清空</span>
            </button>
            <button
              class="btn btn-primary btn-full"
              :disabled="isGenerating"
              @click="generateImage"
            >
              <span v-if="isGenerating" class="loading"></span>
              <span>{{ isGenerating ? '生成中...' : '生成图像' }}</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

interface UploadedFile {
  name: string
  size: number
  file: File
}

interface ApiResponse {
  success: boolean
  data?: any
  message: string
  error?: string
}

interface ImageParams {
  model?: string
  size?: string
  aspect_ratio?: string
  quality?: string
  style_preset?: string
  response_format?: string
  output_format?: string
  n?: number
  watermark?: boolean
  negative_prompt?: string
  image?: string
  strength?: number
  mask?: string
  background?: string
  async_mode?: boolean
  retries?: number
}

// 响应式数据
const uploadedFiles = ref<UploadedFile[]>([])
const promptText = ref('')
const generatedImage = ref<string | null>(null)
const isGenerating = ref(false)
const isDragOver = ref(false)

// DOM引用
const fileInputRef = ref<HTMLInputElement | null>(null)
const imageAreaRef = ref<HTMLDivElement | null>(null)

// API配置
const API_BASE_URL = 'http://localhost:8807/api'

// API调用方法 - 分开的三个独立接口
const apiClient = {
  // 接口1：上传文件并整理内容
  async uploadFiles(files: File[]): Promise<ApiResponse> {
    const formData = new FormData()
    files.forEach((file) => {
      formData.append('files', file)
    })

    try {
      const response = await fetch(`${API_BASE_URL}/upload-files`, {
        method: 'POST',
        body: formData,
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`HTTP ${response.status}: ${errorText}`)
      }

      return await response.json()
    } catch (error) {
      console.error('Upload files error:', error)
      throw error
    }
  },

  // 接口2：优化提示词
  async optimizePrompt(userRequirements: string, fileContent?: string): Promise<ApiResponse> {
    try {
      const response = await fetch(`${API_BASE_URL}/optimize-prompt`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          user_requirements: userRequirements,
          file_content: fileContent,
        }),
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`HTTP ${response.status}: ${errorText}`)
      }

      return await response.json()
    } catch (error) {
      console.error('Optimize prompt error:', error)
      throw error
    }
  },

  // 接口3：生成图像
  async generateImage(prompt: string, params: ImageParams = {}): Promise<ApiResponse> {
    try {
      const response = await fetch(`${API_BASE_URL}/generate-image`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          prompt,
          model: params.model || 'gemini-nano-banana',
          size: params.size || '1024x1024',
          aspect_ratio: params.aspect_ratio || '1:1',
          quality: params.quality || 'medium',
          style_preset: params.style_preset || '3d-model',
          response_format: params.response_format || 'url',
          output_format: params.output_format || 'png',
          n: params.n || 1,
          watermark: params.watermark || false,
          negative_prompt: params.negative_prompt,
          image: params.image,
          strength: params.strength,
          mask: params.mask,
          background: params.background,
          async_mode: params.async_mode || false,
          retries: params.retries || 0,
        }),
      })

      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`HTTP ${response.status}: ${errorText}`)
      }

      return await response.json()
    } catch (error) {
      console.error('Generate image error:', error)
      throw error
    }
  },

  // 健康检查
  async healthCheck(): Promise<boolean> {
    try {
      const response = await fetch(`${API_BASE_URL}/health`, {
        method: 'GET',
      })
      return response.ok
    } catch (error) {
      console.error('Health check failed:', error)
      return false
    }
  },
}

// 触发文件选择
const triggerFileSelect = () => {
  fileInputRef.value?.click()
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (target.files?.length) {
    handleFiles(Array.from(target.files))
  }
}

// 拖拽处理
const handleDragOver = () => {
  isDragOver.value = true
}

const handleDragLeave = () => {
  isDragOver.value = false
}

const handleDrop = (event: DragEvent) => {
  isDragOver.value = false
  if (event.dataTransfer?.files.length) {
    handleFiles(Array.from(event.dataTransfer.files))
  }
}

// 检查文件类型
const isValidFileType = (fileName: string): boolean => {
  const allowedExtensions = ['.doc', '.docx', '.xls', '.xlsx', '.pdf']
  const fileExtension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'))
  return allowedExtensions.includes(fileExtension)
}

// 获取文件图标
const getFileIcon = (fileName: string): string => {
  const extension = fileName.toLowerCase().substring(fileName.lastIndexOf('.'))
  switch (extension) {
    case '.doc':
    case '.docx':
      return '📄'
    case '.xls':
    case '.xlsx':
      return '📊'
    case '.pdf':
      return '📕'
    default:
      return '📄'
  }
}

// 处理文件
const handleFiles = (files: File[]) => {
  const validFiles: File[] = []

  for (const file of files) {
    // 检查文件类型
    if (!isValidFileType(file.name)) {
      alert('请上传Word、Excel或PDF文件')
      continue
    }

    // 检查文件大小
    if (file.size > 10 * 1024 * 1024) {
      alert('文件大小不能超过10MB')
      continue
    }

    // 检查文件数量限制
    if (uploadedFiles.value.length >= 10) {
      alert('最多只能上传10个文件')
      break
    }

    // 检查重复文件
    const isDuplicate = uploadedFiles.value.some((f) => f.name === file.name)
    if (isDuplicate) {
      alert(`文件"${file.name}"已存在`)
      continue
    }

    uploadedFiles.value.push({
      name: file.name,
      size: file.size,
      file,
    })

    validFiles.push(file)
  }

  // 清空input以便再次选择相同文件
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }

  if (validFiles.length > 0) {
    console.log(`成功添加 ${validFiles.length} 个文件`)
  }
}

// 移除文件
const removeFile = (index: number) => {
  const fileName = uploadedFiles.value[index].name
  uploadedFiles.value.splice(index, 1)
  console.log(`已移除文件"${fileName}"`)
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  return (bytes / 1024 / 1024).toFixed(2) + ' MB'
}

// 清空提示词
const clearPrompt = () => {
  promptText.value = ''
}

// 生成图像 - 分步调用三个独立接口
const generateImage = async () => {
  if (uploadedFiles.value.length === 0 && promptText.value.trim() === '') {
    alert('请上传参考文档或输入描述词')
    return
  }

  isGenerating.value = true
  generatedImage.value = null

  try {
    // 检查API健康状态
    const isHealthy = await apiClient.healthCheck()
    if (!isHealthy) {
      throw new Error('无法连接到API服务器，请检查服务器是否启动')
    }

    let fileContent: string | undefined

    // 步骤1：如果有文件，先调用上传文件接口
    if (uploadedFiles.value.length > 0) {
      console.log('步骤1：正在处理上传的文件...')
      const files = uploadedFiles.value.map((f) => f.file)
      const uploadResult = await apiClient.uploadFiles(files)

      if (uploadResult.success) {
        fileContent = uploadResult.data.organized_content
        console.log('✅ 步骤1完成：文件处理成功')
        console.log('整理的文档内容:', fileContent)
      } else {
        throw new Error(`文件处理失败: ${uploadResult.message}`)
      }
    } else {
      console.log('📝 跳过步骤1：没有上传文件')
    }

    // 步骤2：调用优化提示词接口
    console.log('步骤2：正在优化提示词...')
    const promptResult = await apiClient.optimizePrompt(promptText.value, fileContent)

    if (!promptResult.success) {
      throw new Error(`提示词优化失败: ${promptResult.message}`)
    }

    const optimizedPrompt = promptResult.data.optimized_prompt
    console.log('✅ 步骤2完成：提示词优化成功')
    console.log('优化后的提示词:', optimizedPrompt)

    // 步骤3：调用图像生成接口
    console.log('步骤3：正在生成图像...')
    const imageParams: ImageParams = {
      model: 'gemini-nano-banana',
      size: '1024x1024',
      aspect_ratio: '1:1',
      quality: 'high',
      style_preset: 'digital-art',
      n: 1,
      watermark: false,
      negative_prompt: '模糊,低质量,变形,噪点,暗淡',
    }

    const imageResult = await apiClient.generateImage(optimizedPrompt, imageParams)

    if (imageResult.success && imageResult.data?.image_result?.data?.[0]?.url) {
      generatedImage.value = imageResult.data.image_result.data[0].url
      console.log('✅ 步骤3完成：图像生成成功！')
      console.log('生成的图片URL:', generatedImage.value)
    } else {
      throw new Error(`图像生成失败: ${imageResult.message || '未知错误'}`)
    }

    console.log('🎉 所有步骤完成！图片生成成功')
  } catch (error) {
    console.error('❌ 生成图片失败:', error)
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    alert(`生成图片失败: ${errorMsg}`)
  } finally {
    isGenerating.value = false
  }
}

// 单独测试上传文件接口
const testUploadFiles = async () => {
  if (uploadedFiles.value.length === 0) {
    alert('请先上传文件')
    return
  }

  try {
    console.log('测试上传文件接口...')
    const files = uploadedFiles.value.map((f) => f.file)
    const result = await apiClient.uploadFiles(files)

    if (result.success) {
      console.log('✅ 上传文件接口测试成功')
      console.log('整理的内容:', result.data.organized_content)
      alert('文件处理成功！请查看控制台输出')
    } else {
      throw new Error(result.message)
    }
  } catch (error) {
    console.error('❌ 上传文件接口测试失败:', error)
    alert(`测试失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 单独测试优化提示词接口
const testOptimizePrompt = async () => {
  if (promptText.value.trim() === '') {
    alert('请输入描述词')
    return
  }

  try {
    console.log('测试优化提示词接口...')
    const result = await apiClient.optimizePrompt(promptText.value)

    if (result.success) {
      console.log('✅ 优化提示词接口测试成功')
      console.log('优化后的提示词:', result.data.optimized_prompt)
      alert('提示词优化成功！请查看控制台输出')
    } else {
      throw new Error(result.message)
    }
  } catch (error) {
    console.error('❌ 优化提示词接口测试失败:', error)
    alert(`测试失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 下载图片
const downloadImage = async () => {
  if (!generatedImage.value) return

  try {
    const response = await fetch(generatedImage.value)
    const blob = await response.blob()

    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `ai-generated-image-${Date.now()}.png`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    console.log('图片下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    alert('图片下载失败，请重试')
  }
}

// 键盘事件处理
const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl+Enter 快速生成
  if (event.ctrlKey && event.key === 'Enter') {
    if (!isGenerating.value) {
      generateImage()
    }
  }
  // Esc 清空生成结果
  if (event.key === 'Escape') {
    if (!isGenerating.value && generatedImage.value) {
      generatedImage.value = null
    }
  }
  // Ctrl+1 测试上传接口
  if (event.ctrlKey && event.key === '1') {
    testUploadFiles()
  }
  // Ctrl+2 测试优化接口
  if (event.ctrlKey && event.key === '2') {
    testOptimizePrompt()
  }
}

// API健康检查
const checkApiHealth = async () => {
  const isHealthy = await apiClient.healthCheck()
  if (!isHealthy) {
    console.warn('⚠️ 无法连接到API服务器，请检查服务器是否启动')
  } else {
    console.log('✅ API服务器连接正常')
  }
}

// 生命周期
onMounted(() => {
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)

  // 检查API健康状态
  checkApiHealth()

  console.log('🔧 调试快捷键：')
  console.log('  Ctrl + Enter: 生成图像')
  console.log('  Ctrl + 1: 测试上传文件接口')
  console.log('  Ctrl + 2: 测试优化提示词接口')
  console.log('  Esc: 清空生成结果')

  // 初始化示例数据
  setTimeout(() => {
    const exampleFiles: UploadedFile[] = []

    uploadedFiles.value = exampleFiles
    promptText.value = '一只在太空中的猫，戴着宇航员头盔，背景是地球和星星，超现实主义风格'
  }, 500)
})

onUnmounted(() => {
  // 清理事件监听
  document.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.ai-image-generator {
  --primary-blue: #3b82f6;
  --dark-blue: #2563eb;
  --cyan-blue: #06b6d4;
  --dark-cyan: #0891b2;
  --bg-gradient: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(6, 182, 212, 0.05) 100%);
  --base-bg: #f8fafc;
  --card-bg: rgba(255, 255, 255, 0.8);
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-muted: #64748b;
  --success: #10b981;
  --error: #ef4444;

  /* 字体系统 - 紧凑设计 */
  --font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  --font-size-title: 1.5rem;
  --font-size-subtitle: 1.125rem;
  --font-size-body: 0.875rem;
  --font-size-small: 0.75rem;
  --font-size-tiny: 0.6875rem;
  --font-weight-bold: 700;
  --font-weight-semibold: 600;
  --font-weight-medium: 500;

  /* 紧凑布局系统 */
  --max-width: 1000px;
  --spacing-lg: 1.5rem;
  --spacing-md: 3vh;
  --spacing-sm: 0.75rem;
  --spacing-xs: 0.5rem;
  --spacing-xxs: 0.25rem;

  /* 圆角与阴影 */
  --border-radius-lg: 0.75rem;
  --border-radius-md: 0.5rem;
  --border-radius-sm: 0.375rem;
  --shadow-card: 0 2px 8px rgba(59, 130, 246, 0.08);
  --shadow-hover: 0 4px 12px rgba(59, 130, 246, 0.15);

  font-family: var(--font-family);
  font-size: var(--font-size-body);
  line-height: 1.5;
  color: var(--text-primary);
  background-color: var(--base-bg);
  background-image: var(--bg-gradient);
  min-height: 94vh;
  padding: var(--spacing-md);
}

.ai-image-generator::before {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
    radial-gradient(circle at 20% 30%, rgba(59, 130, 246, 0.02) 1px, transparent 1px),
    radial-gradient(circle at 80% 70%, rgba(6, 182, 212, 0.02) 1px, transparent 1px);
  background-size: 60px 60px;
  z-index: -1;
  pointer-events: none;
}

.container {
  max-width: var(--max-width);
  margin: 0 auto;
  display: grid;
  grid-template-columns: 1.8fr 1fr;
  gap: var(--spacing-md);
  height: calc(100vh - 2rem);
  max-height: 700px;
}

/* 主内容区 - AI生图区域 */
.main-content {
  background: var(--card-bg);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-lg);
  box-shadow: var(--shadow-card);
  border: 1px solid rgba(59, 130, 246, 0.1);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  max-height: 700px;
}

.main-header {
  margin-bottom: var(--spacing-md);
  flex-shrink: 0;
}

.main-title {
  font-size: var(--font-size-title);
  font-weight: var(--font-weight-bold);
  line-height: 1.3;
  margin-bottom: var(--spacing-xxs);
  background: linear-gradient(135deg, var(--primary-blue), var(--cyan-blue));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.main-subtitle {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
  line-height: 1.4;
}

.image-area {
  flex: 1;
  background: rgba(255, 255, 255, 0.5);
  border-radius: var(--border-radius-md);
  border: 2px dashed rgba(59, 130, 246, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: var(--spacing-md);
  overflow: hidden;
  position: relative;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-height: 200px;
  max-height: 350px;
}

.image-area:hover {
  border-color: rgba(59, 130, 246, 0.4);
  transform: translateY(-1px);
  box-shadow: var(--shadow-hover);
}

.image-placeholder {
  text-align: center;
  padding: var(--spacing-md);
  color: var(--text-muted);
}

.image-placeholder .icon {
  font-size: 2rem;
  margin-bottom: var(--spacing-xs);
  opacity: 0.6;
}

.image-placeholder p {
  font-size: var(--font-size-small);
  margin-bottom: var(--spacing-xxs);
}

.image-controls {
  display: flex;
  gap: var(--spacing-sm);
  flex-shrink: 0;
}

/* 侧边栏 */
.sidebar {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
  max-height: 700px;
}

/* 上传区域 */
.upload-area {
  background: var(--card-bg);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-md);
  box-shadow: var(--shadow-card);
  border: 1px solid rgba(59, 130, 246, 0.1);
  backdrop-filter: blur(10px);
  flex: 1;
  display: flex;
  flex-direction: column;
  max-height: 320px;
  overflow: hidden;
}

.upload-header {
  margin-bottom: var(--spacing-sm);
  flex-shrink: 0;
}

.upload-title {
  font-size: var(--font-size-subtitle);
  font-weight: var(--font-weight-semibold);
  line-height: 1.3;
  margin-bottom: var(--spacing-xxs);
  color: var(--text-primary);
}

.upload-subtitle {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
  line-height: 1.4;
}

.upload-box {
  border: 2px dashed rgba(59, 130, 246, 0.3);
  border-radius: var(--border-radius-md);
  padding: var(--spacing-sm);
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  margin-bottom: var(--spacing-sm);
  min-height: 80px;
  flex-shrink: 0;
}

.upload-box:hover,
.upload-box.drag-over {
  border-color: var(--primary-blue);
  background: rgba(59, 130, 246, 0.03);
  transform: translateY(-1px);
}

.upload-icon {
  font-size: 1.5rem;
  margin-bottom: var(--spacing-xxs);
  color: var(--primary-blue);
}

.upload-text {
  margin-bottom: var(--spacing-xxs);
  color: var(--text-secondary);
  font-size: var(--font-size-small);
}

.file-list {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.file-list::-webkit-scrollbar {
  width: 4px;
}

.file-list::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 2px;
}

.file-list::-webkit-scrollbar-thumb {
  background: var(--primary-blue);
  border-radius: 2px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-xs);
  border-radius: var(--border-radius-sm);
  margin-bottom: var(--spacing-xxs);
  background: rgba(255, 255, 255, 0.6);
  transition: all 0.2s ease;
}

.file-item:hover {
  background: rgba(59, 130, 246, 0.05);
}

.file-icon {
  margin-right: var(--spacing-xs);
  color: var(--primary-blue);
  font-size: var(--font-size-small);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: var(--font-size-small);
  font-weight: var(--font-weight-medium);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: var(--font-size-tiny);
  color: var(--text-muted);
}

.remove-btn {
  background: none;
  border: none;
  font-size: 1rem;
  color: var(--text-muted);
  cursor: pointer;
  padding: 0.125rem;
  border-radius: 50%;
  transition: all 0.2s ease;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.remove-btn:hover {
  background: rgba(239, 68, 68, 0.1);
  color: var(--error);
}

/* 输入区域 */
.input-area {
  background: var(--card-bg);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-md);
  box-shadow: var(--shadow-card);
  border: 1px solid rgba(59, 130, 246, 0.1);
  backdrop-filter: blur(10px);
  flex: 1;
  display: flex;
  flex-direction: column;
  max-height: 320px;
  overflow: hidden;
}

.input-header {
  margin-bottom: var(--spacing-sm);
  flex-shrink: 0;
}

.input-title {
  font-size: var(--font-size-subtitle);
  font-weight: var(--font-weight-semibold);
  line-height: 1.3;
  margin-bottom: var(--spacing-xxs);
  color: var(--text-primary);
}

.input-subtitle {
  font-size: var(--font-size-small);
  color: var(--text-secondary);
  line-height: 1.4;
}

.prompt-container {
  flex: 1;
  min-height: 0;
  margin-bottom: var(--spacing-sm);
  max-height: 180px;
  overflow: hidden;
}

.prompt-input {
  width: 90%;
  height: 80%;
  padding: var(--spacing-sm);
  border: 1px solid rgba(59, 130, 246, 0.2);
  border-radius: var(--border-radius-md);
  font-family: inherit;
  font-size: var(--font-size-small);
  resize: none;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(255, 255, 255, 0.7);
  line-height: 1.5;
}

.prompt-input::-webkit-scrollbar {
  width: 4px;
}

.prompt-input::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.05);
  border-radius: 2px;
}

.prompt-input::-webkit-scrollbar-thumb {
  background: var(--primary-blue);
  border-radius: 2px;
}

.prompt-input:focus {
  outline: none;
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.input-controls {
  display: flex;
  gap: var(--spacing-xs);
  flex-shrink: 0;
}

/* 按钮样式 */
.btn {
  padding: 0.625rem 1rem;
  border-radius: var(--border-radius-md);
  font-weight: var(--font-weight-semibold);
  font-size: var(--font-size-small);
  border: none;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 80px;
  text-align: center;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-xxs);
  white-space: nowrap;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
  color: white;
  box-shadow: 0 2px 4px rgba(59, 130, 246, 0.2);
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: var(--shadow-hover);
}

.btn-secondary {
  background: transparent;
  color: var(--primary-blue);
  border: 1px solid var(--primary-blue);
  backdrop-filter: blur(10px);
}

.btn-secondary:hover:not(:disabled) {
  background: rgba(59, 130, 246, 0.05);
  transform: translateY(-1px);
}

.btn-full {
  flex: 1;
}

.text-muted {
  color: var(--text-muted);
}

/* 加载动画 */
.loading {
  display: inline-block;
  width: 14px;
  height: 14px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

/* 生成图片样式 */
.generated-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: var(--border-radius-sm);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .container {
    grid-template-columns: 1fr;
    height: auto;
    max-height: none;
  }

  .main-content {
    max-height: 450px;
  }

  .sidebar {
    flex-direction: row;
    max-height: 300px;
  }

  .upload-area,
  .input-area {
    flex: 1;
    max-height: 280px;
  }

  .prompt-container {
    max-height: 150px;
  }
}

@media (max-width: 768px) {
  .ai-image-generator {
    padding: var(--spacing-sm);
  }

  .container {
    gap: var(--spacing-sm);
    max-height: 600px;
  }

  .sidebar {
    flex-direction: column;
    max-height: 500px;
  }

  .upload-area,
  .input-area {
    max-height: 240px;
  }

  .prompt-container {
    max-height: 120px;
  }

  .image-controls,
  .input-controls {
    flex-direction: column;
  }

  .btn {
    min-width: 100%;
  }

  .main-title {
    font-size: 1.25rem;
  }

  .image-area {
    min-height: 180px;
    max-height: 280px;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding: var(--spacing-md);
    max-height: 350px;
  }

  .upload-area,
  .input-area {
    padding: var(--spacing-sm);
    max-height: 200px;
  }

  .prompt-container {
    max-height: 100px;
  }

  .image-area {
    min-height: 150px;
    max-height: 220px;
  }
}
</style>
